/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package blms.repository.inmemory;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import blms.domain.League;
import blms.exception.LeagueDoesNotExistException;
import blms.repository.LeagueRepository;
import blms.util.BLMSMessages;

/**
 * Simple in-memory repository of leagues. This implementation may be used to
 * load and store leagues either in memory.
 * 
 * @author João Arthur
 * @author Jonhnny Weslley
 * @author Thiago Emmanuel
 * @version 1.00, 21/04/2008
 * @since 1.0
 */
public class InMemoryLeagueRepository extends
		InMemoryRepositoryWithAutoIncrementId<League> implements
		LeagueRepository {

	/*
	 * (non-Javadoc)
	 * 
	 * @see blms.repository.LeagueRepository#containsLeagueName(java.lang.String)
	 */
	public boolean containsLeagueName(final String name) {
		final Collection<League> leagues = getAll();
		for (final League league : leagues) {
			if (league.getName().equals(name)) {
				return true;
			}
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see blms.repository.LeagueRepository#findLeagueByName(java.lang.String)
	 */
	public List<String> findLeagueByName(final String name)
			throws LeagueDoesNotExistException {

		final List<String> returnValue = new LinkedList<String>();

		Matcher matcher;
		String leagueName;

		final Collection<League> leagues = getAll();

		final Pattern p = Pattern.compile(name, Pattern.CASE_INSENSITIVE);

		for (final League league : leagues) {
			leagueName = league.getName();
			matcher = p.matcher(leagueName);
			if (matcher.matches()) {
				returnValue.add(leagueName);
			}
		}

		if (returnValue.isEmpty()) {
			throw new LeagueDoesNotExistException(
					BLMSMessages.COULD_NOT_FIND_LEAGUE_MESSAGE + " " + name);
		}

		Collections.sort(returnValue);
		return returnValue;
	}

}
